package de.wbh.gwt.form.layouter.java.server.servlet.rpc;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.imageio.ImageIO;

import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.google.gwt.rpc.server.RpcServlet;

import de.wbh.gwt.form.layouter.gwt.rpc.EdgeDetectionService;
import de.wbh.gwt.form.layouter.java.server.ConfigurationHelper;
import de.wbh.gwt.form.layouter.java.server.SobelFunction;
import de.wbh.gwt.form.layouter.shared.Box;

public class EdgeDetectionServiceImpl extends RpcServlet implements EdgeDetectionService {

	private static final long serialVersionUID = 4558284841437003239L;
	private static String dir = ConfigurationHelper.getInstance().getHomeDirectory();

	@Override
	public List<Box> getEdges(String fileName) {
		String fullFileName = dir + "\\image\\" + fileName + ".png";
		try {
			BufferedImage image = ImageIO.read(new File(fullFileName));
			String[] boxesStringArray = SobelFunction.sobelKanten(image);

			int imageWidth = image.getWidth();

			List<Box> boxes = Lists.newArrayList();
			System.err.println("entries in array: " + boxesStringArray.length);
			for (String boxString : boxesStringArray) {
				Box box = new Box();
				Iterator<String> it = Splitter.on(";").split(boxString).iterator();
				String start = it.next();
				String width = it.next();
				String height = it.next();

				box.x = Integer.parseInt(start) % imageWidth;
				box.y = Integer.parseInt(start) / imageWidth;
				box.width = Integer.parseInt(width);
				box.height = Integer.parseInt(height);

				boxes.add(box);
			}
			System.err.println("found " + boxes.size() + " boxes");
			return boxes;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

}
